package com.example.nbshopping.com.example.nbshopping.login_reg;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import com.example.nbshopping.utils.BaseActivity;
import com.example.nbshopping.MeFragment;
import com.example.nbshopping.R;
import com.example.nbshopping.utils.ChangeHeadDialog;
import com.example.nbshopping.utils.EditUserDialog;
import com.example.nbshopping.utils.SaveUserUtils;
import com.example.nbshopping.utils.URLUtils;
import com.google.gson.Gson;

import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/*个人中心*/
public class PersonCenterActivity extends BaseActivity {
    private UserBean.DataBean userInfo;
    ImageView ibtn_backToMe, ibtn_edit_nknm, ibtn_edit_name, ibtn_edit_addr, ibtn_edit_head;
    TextView saveTv, telTv, addrTv, nameTv, nicknameTv;
    UserBean.DataBean newUserInfo;   //保存之后的对象信息
    String imgpath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_center);
        userInfo = SaveUserUtils.getUserInfo(this);//获取用户保存的信息
        newUserInfo = new UserBean.DataBean(userInfo.getId(), userInfo.getPhone(), userInfo.getPassword(),
                userInfo.getName(), userInfo.getAddress(), userInfo.getNickname(), userInfo.getQuestion(),
                userInfo.getAnswer());
        initView();             //初始化
        setListener();          //设置监听
        setView();              //设置View显示的内容
    }

    private void setView() {

        nicknameTv.setText(userInfo.getNickname());
        nameTv.setText(userInfo.getName());
        telTv.setText(userInfo.getPhone());
        addrTv.setText(userInfo.getAddress());
        File file = new File(imgpath);
        //显示头像
        if (file.exists()) {//如果文件存在
            Bitmap bitmap = BitmapFactory.decodeFile(imgpath);
            ibtn_edit_head.setImageBitmap(bitmap);
        } else {
            ibtn_edit_head.setImageResource(R.mipmap.icon);
        }

    }

    private void setListener() {
        ibtn_backToMe.setOnClickListener(listener);
        ibtn_edit_nknm.setOnClickListener(listener);
        ibtn_edit_name.setOnClickListener(listener);
        ibtn_edit_addr.setOnClickListener(listener);
        ibtn_edit_head.setOnClickListener(listener);
        saveTv.setOnClickListener(listener);
    }

    //创建监听对象
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();//获取到被点击的Id
            switch (v.getId()) {
                case R.id.center_iv_back://返回按钮回到“我的”界面
                    if (isSameObj()) {
                        finish();
                    } else {
                        showBackDialog();
                    }
                    break;

                //修改头像
                case R.id.center_iv_head:
                    showChangeHeadDialog();
                    break;

                //昵称
                case R.id.center_iv_nickname:
                    String hint = "请输入修改的贝壳昵称：";
                    showEditUserDialog(hint, nicknameTv);
                    break;

                //收货姓名
                case R.id.center_iv_name:
                    hint = "请输入修改的收货姓名：";
                    showEditUserDialog(hint, nameTv);
                    break;

                //修改收货地址
                case R.id.center_iv_address:
                    hint = "请输入修改的收货地址：";
                    showEditUserDialog(hint, addrTv);
                    break;

                case R.id.center_tv_save://保存
                    boolean isSameObj = isSameObj();
                    if (isSameObj) {
                        Toast.makeText(PersonCenterActivity.this, "已保存最新内容！", Toast.LENGTH_SHORT).show();
                    } else {
                        Map<String, String> map = new HashMap<>();
                        map.put("id", newUserInfo.getId() + "");
                        map.put("address", newUserInfo.getAddress());
                        map.put("nickname", newUserInfo.getNickname());
                        map.put("name", newUserInfo.getName());
                        postNetwork(URLUtils.updateInfo_url, map);
                    }
                    break;
                default:
                    break;
            }
        }


        private void onClickBack(View v) {
            //返回按钮处理逻辑
            //从当前个人中心界面跳转到“我的”首页碎片——MeFragment
            Intent intent = new Intent(PersonCenterActivity.this, MeFragment.class);
            startActivity(intent);
        }
    };

    //显示对话框
    private void showChangeHeadDialog() {
        ChangeHeadDialog headDialog = new ChangeHeadDialog(this);
        headDialog.show();
        headDialog.setDialogWidth();
        headDialog.setOnChangeheadListener(new ChangeHeadDialog.OnChangeheadListener() {
            @Override
            public void clickCamera() {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 100);
            }

            @Override
            public void clickLocal() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 100) {
            Bundle bundle = data.getExtras();
            Bitmap bm = (Bitmap) bundle.get("data");
            ibtn_edit_head.setImageBitmap(bm);
            saveBitmap(bm);
        }
    }

    private void saveBitmap(Bitmap bm) {
        try {
            FileOutputStream fos = new FileOutputStream(imgpath);
            bm.compress(Bitmap.CompressFormat.JPEG, 80, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    //弹出返回对话框：内容改变了，但是没有保存
    private void showBackDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息");
        builder.setMessage("当前页面数据有变且未保存，是否仍返回上级页面？");
        builder.setIcon(R.mipmap.icon);
        builder.setPositiveButton("取消", null);
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();//结束当前页面
            }
        });
        builder.create().show();
    }

    @Override
    public void onSuccess(String result) {
        super.onSuccess(result);
        UserBean jsonbean = new Gson().fromJson(result, UserBean.class);
        switch (jsonbean.getCode()) {
            case 200:
                SaveUserUtils.saveUserToFile(this, newUserInfo);
                userInfo = SaveUserUtils.getUserInfo(this);
                Toast.makeText(PersonCenterActivity.this, "更新内容成功！", Toast.LENGTH_SHORT).show();
                break;
            default:
                Toast.makeText(PersonCenterActivity.this, "更新内容失败！", Toast.LENGTH_SHORT).show();
                break;
        }
    }


    private boolean isSameObj() {

        String nknm = nicknameTv.getText().toString().trim();
        String addr = addrTv.getText().toString().trim();
        String name = nameTv.getText().toString().trim();
        newUserInfo.setAddress(addr);
        newUserInfo.setNickname(nknm);
        newUserInfo.setName(name);
        return newUserInfo.equals(userInfo);

    }

    private void showEditUserDialog(String hint, final TextView tv) {
//        1.创建对话框对象
        final EditUserDialog dialog = new EditUserDialog(this);
//        2.显示对话框
        dialog.show();
//        3.设置参数
        dialog.setDialogWidth();
        dialog.setTipHint(hint);
        dialog.setOnEnsureListener(new EditUserDialog.OnEnsureListener() {
            @Override
            public void onEnsure(String msg) {
                tv.setText(msg);
                dialog.cancel();
            }
        });
    }

    private void initView() {
        ibtn_backToMe = (ImageView) findViewById(R.id.center_iv_back);
        ibtn_edit_nknm = (ImageView) findViewById(R.id.center_iv_nickname);
        ibtn_edit_name = (ImageView) findViewById(R.id.center_iv_name);
        ibtn_edit_addr = (ImageView) findViewById(R.id.center_iv_address);
        ibtn_edit_head = (ImageView) findViewById(R.id.center_iv_head);
        ibtn_edit_addr = (ImageView) findViewById(R.id.center_iv_address);
        nicknameTv = (TextView) findViewById(R.id.center_tv_nickname);
        nameTv = (TextView) findViewById(R.id.center_tv_name);
        addrTv = (TextView) findViewById(R.id.center_tv_address);
        telTv = (TextView) findViewById(R.id.center_tv_tel);
        saveTv = (TextView) findViewById(R.id.center_tv_save);


    }
}

